﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Communication.Base;
using UtilZ.Dotnet.Ex.Communication.Net.Base;
using UtilZ.Dotnet.Ex.Model;

namespace UtilZ.Dotnet.Ex.Communication.Net.Ftp
{
    /// <summary>
    /// ftp服务器主动连接ftp客户端
    /// </summary>
    internal class FtpPortDataTranfer : FtpDataTranferAbs
    {
        private readonly EndPoint _clientListenEndPoint;

        /// <summary>
        /// 构造函数
        /// </summary>
        public FtpPortDataTranfer(FtpSession session, EndPoint clientListenEndPoint)
            : base(session)
        {
            this._clientListenEndPoint = clientListenEndPoint;
        }



        /// <summary>
        /// 创建tcp连接
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="append">true:追加数据到已存在的文件,文件不存在则创建;false:总是创建新文件,如果旧文件存在则替换</param>
        /// <returns>创建的tcp连接</returns>
        protected override FtpTransferClient PrimitiveCreateTcpClient(string filePath, bool append)
        {
#if NET4_0
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
#else
            Socket client = new Socket(SocketType.Stream, ProtocolType.Tcp);       
#endif

            var portModePort = base._session.FtpServer.Config.PortModePort;
            if (portModePort > 0)
            {
                client.Bind(new IPEndPoint(IPAddress.Any, portModePort));
            }
            client.Connect(this._clientListenEndPoint);
            return new FtpTransferClient(client, this._session, append, filePath);
        }

        /// <summary>
        /// 获取ftp响应
        /// </summary>
        /// <returns>ftp响应</returns>
        protected override IFtpResponse PrimitiveGetFtpResponse()
        {
            //Response: 200 PORT command successful. Consider using PASV. # 表示命令执行成功， 这里是端口连接成功
            return new FtpCodeResponse(FtpStatusCodes.Code200, "200 PORT command successful. Consider using PASV.");
        }
    }
}
